﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CMS6Tools.Common.Email
{
    public class TextTemplateExtraData : ITextTemplateExtraData
    {
        public TextTemplateExtraData()
            : this(new Dictionary<string, string>(), new Dictionary<int, IDictionary<string, string>>())
        {
        }

        public TextTemplateExtraData(IDictionary<string, string> dict)
            : this(dict ?? new Dictionary<string, string>(), new Dictionary<int, IDictionary<string, string>>())
        {
        }


        public TextTemplateExtraData(IDictionary<string, string> dict, IDictionary<int, IDictionary<string, string>> tableDict)
        {
            DataDictionary = dict ?? new Dictionary<string, string>();
            TableDataDictionary = tableDict ?? new Dictionary<int, IDictionary<string, string>>();
        }

        protected IDictionary<int, IDictionary<string, string>> TableDataDictionary { get; private set; }
        protected IDictionary<string, string> DataDictionary { get; private set; }

        public virtual string GetValue(string key)
        {
            var returnValue = default(string);
            if (DataDictionary.TryGetValue(key, out returnValue))
                return returnValue ?? string.Empty;
            return string.Empty;
        }

        public virtual string GetTableDataValue(int rowIndex, string columnName)
        {
            var dict = default(IDictionary<string, string>);
            if (TableDataDictionary.TryGetValue(rowIndex, out dict) && dict != null)
            {
                var returnValue = default(string);
                if (dict.TryGetValue(columnName, out returnValue))
                    return returnValue ?? string.Empty;
            }

            return string.Empty;
        }

        public void Add(string key, string value, bool replaceExisted = true)
        {
            if (replaceExisted)
            {
                DataDictionary[key] = value;
            }
            else
            {
                if (!DataDictionary.ContainsKey(key))
                    DataDictionary[key] = value;
            }
        }

        public void AddDictionary(int key, IDictionary<string, string> dictionary, bool replaceExisted = true)
        {
            if (replaceExisted)
            {
                TableDataDictionary[key] = dictionary;
            }
            else
            {
                if (!TableDataDictionary.ContainsKey(key))
                    TableDataDictionary[key] = dictionary;
            }
        }
    }
}
